package business_example_service

import (
	"runtime/debug"

	"gitee.com/Luna-CY/Golang-Project-Template/internal/context"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/errors"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/interface/service"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/logger"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/util/pointer"
	"gitee.com/Luna-CY/Golang-Project-Template/model"
	gonanoid "github.com/matoous/go-nanoid"
)

func (cls *Example) CreateExample(ctx context.Context, name string, value uint64, fields ...service.BusinessExampleField) (*model.BusinessExample, errors.Error) {
	if "" == name || 0 == value {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("ISE_LE.E_LE.CE_LE.162831 name is %s value is %d stack %s", name, value, string(debug.Stack()))

		return nil, errors.ErrorServerInternalError("ISE_LE.E_LE.CE_LE.173145", "异常的传入参数")
	}

	var example = new(model.BusinessExample)
	example.Id = gonanoid.MustID(64)
	example.Name = pointer.New(name)
	example.Value = pointer.New(value)

	for _, field := range fields {
		if err := field(example); nil != err {
			return nil, err.Relation(errors.ErrorServerInternalError("ISE_LE.E_LE.CE_LE.292800", "应用选项失败"))
		}
	}

	if err := cls.example.SaveBusinessExample(ctx, example); nil != err {
		return nil, err.Relation(errors.ErrorServerInternalError("ISE_LE.E_LE.CE_LE.273151", "保存数据失败"))
	}

	return example, nil
}
